package org.example.leetcode.addon.lc90;

import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class Solution {
    List<List<Integer>> ans = new LinkedList<>();
    Deque<Integer> path = new LinkedList<>();
    boolean[] used;

    public List<List<Integer>> subsetsWithDup(int[] nums) {
        if (nums == null || nums.length == 0) {
            ans.add(new LinkedList<>(path));
            return ans;
        }

        used = new boolean[nums.length];
        Arrays.sort(nums);
        backtracking(nums, 0);

        return ans;
    }

    private void backtracking(int[] nums, int startIndex) {
        ans.add(new LinkedList<>(path));
        if (startIndex >= nums.length) {
            return;
        }

        for (int i = startIndex; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]){
                continue;
            }

            path.add(nums[i]);
            used[i] = true;
            backtracking(nums, i + 1);
            used[i] = false;
            path.removeLast();
        }
    }
}
